package com.ruoyi.web.web.api;

import com.ruoyi.web.core.config.AppConf;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Random;
import java.util.UUID;

@Controller("fileControllerApi")
@RequestMapping("/api/file")
public class FileController {
    private Random random = new Random();

    /***
     * 上传文件
     * @param file
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file, HttpSession session) throws Exception {

        String level1 = (file.hashCode() &  0X3FF) + "";
        String level2 = (new Long((System.currentTimeMillis() + random.nextInt(1024))).hashCode() &  0X3FF) + "";
        String level3 = (new Long((System.currentTimeMillis() + random.nextInt(1024))).hashCode() &  0X3FF) + "";
        String level4 = (new Long((System.currentTimeMillis() + random.nextInt(1024))).hashCode() &  0X3FF) + "";

        String randomPath = level1 + "/" + level2 + "/" + level3 + "/" + level4+"/";
        if(!new File(AppConf.getUploadPath()+randomPath).exists()) {
            new File(AppConf.getUploadPath()+randomPath).mkdirs();
        }

        String randomName = UUID.randomUUID().toString();
        randomPath += randomName.replace("-", "")+"-"+file.getOriginalFilename();

        File path = new File(AppConf.getUploadPath()+randomPath);

        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path));
        byte[] buffer = new byte[1024 * 5]; int len = 0;
        InputStream in = file.getInputStream();
        while((len = in.read(buffer)) != -1) {
            out.write(buffer,0,len);
            out.flush();
        }
        out.close();


        session.setAttribute(randomName, randomPath);

        return randomName;
    }
}
